from starlette.middleware import Middleware
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.wsgi import WSGIMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.authentication import AuthenticationMiddleware
import time


# 这里是改写middleware的实例，注意必须重新dispatch
class AddProcessTimeHeaderMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        start_time = time.time()
        responser = await call_next(request)
        process_time = round(time.time() - start_time, 4)
        # 返回接口响应时间
        responser.headers["X-Process-Time"] = f"{process_time} (s)"
        return responser


# 为app注册Middleware即可
app_middleware = [
    Middleware(AddProcessTimeHeaderMiddleware)
]
#
#
# app = FastAPI(middleware=app_middleware)
FastApiConfig = {
    "middleware": app_middleware
}
